package me.chan.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by JanGin on 2017/6/10.
 */
public class PropertiesUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);

    public static Properties loadProperties(String filename){
        Properties props = null;
        InputStream in = null;
        try {
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
            if (null == in) {
                throw new FileNotFoundException(filename + "could not found");
            }
            props = new Properties();
            props.load(in);
        }catch (IOException e) {
            LOGGER.error("load properties file failure", e);
        } finally {
            if (in != null) {
                try {
                  in.close();
                } catch (IOException e) {
                    LOGGER.error("close inputstream failure");
                }
            }
        }
        return props;
    }

    public static String getStringProperty(Properties props, String propertyKey) {
       return getStringProperty(props, propertyKey, "");
    }

    public static String getStringProperty(Properties props, String propertyKey, String defaultValue) {
        String value = defaultValue;
        if (props.containsKey(propertyKey)) {
            value = props.getProperty(propertyKey);
        }
        return value;
    }

    public static int getIntegerProperty(Properties props, String propertyKey) {
        return getIntegerProperty(props, propertyKey, 0);
    }

    public static int getIntegerProperty(Properties props, String propertyKey, int defaultValue ) {
        int value = defaultValue;
        if (props.containsKey(propertyKey)) {
            value = (Integer)props.get(propertyKey);
        }
        return value;
    }

    public static boolean getBoolProperty(Properties props, String propertyKey) {
        return getBoolProperty(props, propertyKey, false);
    }

    public static boolean getBoolProperty(Properties props, String propertyKey, boolean defaultValue) {
        boolean value = defaultValue;
        if (props.containsKey(propertyKey)) {
            value = (Boolean) props.get(propertyKey);
        }
        return value;
    }
}
